﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _002_小说目录名转换
{
    public partial class Form1 : Form
    {
        private Thread MyThread;

        private delegate void SetRichMsg(string msg);
        SetRichMsg setRichMsg;

        public Form1()
        {
            InitializeComponent();
            this.setRichMsg = new SetRichMsg(SetRichText);
        }

        public void SetRichText(string msg)
        {
            this.MsgRich.AppendText(msg);
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                this.TxtPath.Text = fileDialog.FileName;
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            MyThread = new Thread(() => DoWork(this.TxtPath.Text));
            MyThread.Start();
            this.MsgRich.Focus();
        }

        private void DoWork(string path)
        {
            this.Invoke(this.setRichMsg, "开始转换：\n");
            this.Invoke(this.setRichMsg, path + '\n');

            FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            StreamReader streamReader = new StreamReader(fileStream);
            string txtWord = streamReader.ReadToEnd();
            for (int i = 1; i <= 1000; i++)
            {
                txtWord = txtWord.Replace("\n" + i + "、", "\n第" + i + "章 ");
                this.Invoke(this.setRichMsg, i + " ");
            }
            this.Invoke(this.setRichMsg, "\n替换完成");

            //清空文本
            fileStream.Seek(0, SeekOrigin.Begin);
            fileStream.SetLength(0);
            this.Invoke(this.setRichMsg, "\n清空完成");
            //写入文本
            StreamWriter streamWriter = new StreamWriter(fileStream);
            streamWriter.Write(txtWord);
            this.Invoke(this.setRichMsg, "\n写入完成");
            //关闭流
            streamWriter.Close();
            streamReader.Close();
            fileStream.Close();
        }
    }
}
